const { query } = require('../config/mysqlConfig');
const User = require('../models/User');

// 获取用户的所有好友
const getUserFriends = async (userId) => {
  try {
    console.log('获取用户好友列表, userId:', userId);
    const friendRecords = await query(
      'SELECT friend_id FROM friends WHERE user_id = ?',
      [userId]
    );
    
    if (!friendRecords.length) {
      console.log('该用户没有好友');
      return [];
    }
    
    // 获取所有好友的ID
    const friendIds = friendRecords.map(record => record.friend_id);
    console.log('好友IDs:', friendIds);
    
    // 从MongoDB获取用户详细信息
    const friends = await User.find(
      { _id: { $in: friendIds } },
      'username email avatar status'
    );
    
    console.log(`找到${friends.length}个好友`);
    return friends;
  } catch (error) {
    console.error('获取好友列表失败:', error);
    throw error;
  }
};

// 添加好友关系（双向）
const addFriendship = async (userId, friendId) => {
  try {
    console.log(`添加好友关系: ${userId} <-> ${friendId}`);
    // 开始事务
    const connection = await require('../config/mysqlConfig').pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 添加用户 -> 好友 的关系
      await connection.query(
        'INSERT INTO friends (user_id, friend_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE created_at = CURRENT_TIMESTAMP',
        [userId, friendId]
      );
      
      // 添加好友 -> 用户 的关系
      await connection.query(
        'INSERT INTO friends (user_id, friend_id) VALUES (?, ?) ON DUPLICATE KEY UPDATE created_at = CURRENT_TIMESTAMP',
        [friendId, userId]
      );
      
      // 提交事务
      await connection.commit();
      connection.release();
      console.log('好友关系添加成功');
      return true;
    } catch (err) {
      // 回滚事务
      await connection.rollback();
      connection.release();
      console.error('事务执行失败:', err);
      throw err;
    }
  } catch (error) {
    console.error('添加好友关系失败:', error);
    throw error;
  }
};

// 删除好友关系（双向）
const removeFriendship = async (userId, friendId) => {
  try {
    // 开始事务
    const connection = await require('../config/mysqlConfig').pool.getConnection();
    await connection.beginTransaction();
    
    try {
      // 删除用户 -> 好友 的关系
      await connection.query(
        'DELETE FROM friends WHERE user_id = ? AND friend_id = ?',
        [userId, friendId]
      );
      
      // 删除好友 -> 用户 的关系
      await connection.query(
        'DELETE FROM friends WHERE user_id = ? AND friend_id = ?',
        [friendId, userId]
      );
      
      // 提交事务
      await connection.commit();
      connection.release();
      return true;
    } catch (err) {
      // 回滚事务
      await connection.rollback();
      connection.release();
      throw err;
    }
  } catch (error) {
    console.error('删除好友关系失败:', error);
    throw error;
  }
};

// 检查是否已经是好友
const checkFriendship = async (userId, friendId) => {
  try {
    const result = await query(
      'SELECT COUNT(*) as count FROM friends WHERE user_id = ? AND friend_id = ?',
      [userId, friendId]
    );
    
    return result[0].count > 0;
  } catch (error) {
    console.error('检查好友关系失败:', error);
    throw error;
  }
};

// 获取用户的好友请求（发送或接收的）
const getFriendRequests = async (userId) => {
  try {
    console.log('获取用户好友请求, userId:', userId);
    // 获取接收到的好友请求
    const requests = await query(
      `SELECT fr.id, fr.from_user_id, fr.status, fr.created_at 
       FROM friend_requests fr 
       WHERE fr.to_user_id = ? AND fr.status = 'pending'`,
      [userId]
    );
    
    if (!requests.length) {
      console.log('该用户没有待处理的好友请求');
      return [];
    }
    
    // 获取发送请求的用户IDs
    const senderIds = requests.map(req => req.from_user_id);
    console.log('发送好友请求的用户IDs:', senderIds);
    
    // 从MongoDB获取用户详细信息
    const senders = await User.find(
      { _id: { $in: senderIds } },
      'username email avatar'
    );
    
    // 整合数据
    const requestsWithUserInfo = requests.map(req => {
      const sender = senders.find(s => s._id.toString() === req.from_user_id);
      if (!sender) {
        console.log(`警告: 未找到ID为${req.from_user_id}的用户信息`);
      }
      return {
        _id: req.id.toString(),
        from: sender || { _id: req.from_user_id, username: '未知用户', avatar: '' },
        status: req.status,
        createdAt: req.created_at
      };
    });
    
    console.log(`找到${requestsWithUserInfo.length}个好友请求`);
    return requestsWithUserInfo;
  } catch (error) {
    console.error('获取好友请求失败:', error);
    throw error;
  }
};

// 发送好友请求
const sendFriendRequest = async (fromUserId, toUserId) => {
  try {
    // 检查是否已经是好友
    const isFriend = await checkFriendship(fromUserId, toUserId);
    if (isFriend) {
      throw new Error('已经是好友了');
    }
    
    // 检查是否已经有待处理的请求
    const existingRequests = await query(
      `SELECT id, status FROM friend_requests 
       WHERE (from_user_id = ? AND to_user_id = ?) OR (from_user_id = ? AND to_user_id = ?)`,
      [fromUserId, toUserId, toUserId, fromUserId]
    );
    
    if (existingRequests.length > 0) {
      const request = existingRequests[0];
      if (request.status === 'pending') {
        throw new Error('已经有一个待处理的好友请求');
      } else if (request.status === 'rejected') {
        // 如果之前的请求被拒绝，可以重新发送
        await query(
          `DELETE FROM friend_requests WHERE id = ?`,
          [request.id]
        );
      }
    }
    
    // 创建新请求
    await query(
      `INSERT INTO friend_requests (from_user_id, to_user_id, status) VALUES (?, ?, 'pending')`,
      [fromUserId, toUserId]
    );
    
    return { success: true, message: '好友请求已发送' };
  } catch (error) {
    console.error('发送好友请求失败:', error);
    throw error;
  }
};

// 响应好友请求
const respondToFriendRequest = async (requestId, userId, action) => {
  try {
    // 验证请求存在且属于当前用户
    const requests = await query(
      `SELECT * FROM friend_requests WHERE id = ? AND to_user_id = ?`,
      [requestId, userId]
    );
    
    if (requests.length === 0) {
      throw new Error('好友请求不存在');
    }
    
    const request = requests[0];
    
    // 更新请求状态
    await query(
      `UPDATE friend_requests SET status = ? WHERE id = ?`,
      [action, requestId]
    );
    
    // 如果接受请求，添加好友关系
    if (action === 'accepted') {
      await addFriendship(userId, request.from_user_id);
    }
    
    return { 
      success: true, 
      message: `好友请求已${action === 'accepted' ? '接受' : '拒绝'}`,
      requesterId: request.from_user_id
    };
  } catch (error) {
    console.error('响应好友请求失败:', error);
    throw error;
  }
};

// 同步用户资料更新
const syncUserProfileToFriends = async (userId, updateData) => {
  try {
    console.log(`同步用户资料更新: ${userId}`, updateData);
    // 这个函数只是为了记录用户资料更新，因为MongoDB已经更新了用户数据
    // 在此处你可以进行额外的操作，比如通知好友或其他跨数据库同步
    return true;
  } catch (error) {
    console.error('同步用户资料失败:', error);
    return false;
  }
};

// 获取用户的所有好友ID列表
const getUserFriendsIds = async (userId) => {
  try {
    console.log('获取用户好友ID列表, userId:', userId);
    const friendRecords = await query(
      'SELECT friend_id FROM friends WHERE user_id = ?',
      [userId]
    );
    
    if (!friendRecords.length) {
      console.log('该用户没有好友');
      return [];
    }
    
    // 获取所有好友的ID
    const friendIds = friendRecords.map(record => record.friend_id);
    console.log(`找到${friendIds.length}个好友ID`);
    return friendIds;
  } catch (error) {
    console.error('获取好友ID列表失败:', error);
    throw error;
  }
};

module.exports = {
  getUserFriends,
  addFriendship,
  removeFriendship,
  checkFriendship,
  getFriendRequests,
  sendFriendRequest,
  respondToFriendRequest,
  syncUserProfileToFriends,
  getUserFriendsIds
}; 